package com.zzq.demo.cron.handler;

import com.google.common.collect.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : zhaoziqian
 * @description :
 * @date : 2019/8/2 9:13
 */
@Slf4j
@JobHandler(value = "shardingJobHandler")
@Component
public class ShardingJobHandler extends IJobHandler {


    @Override
    public ReturnT<String> execute(String param) throws Exception {
        ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
        int index = shardingVO.getIndex();
        int total = shardingVO.getTotal();
        XxlJobLogger.log("分片参数：当前分片序号 = {}, 总分片数 = {}", index, total);
        log.info("分片参数：当前分片序号 = {}, 总分片数 = {}", index, total);

        List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

        List<Integer> jobs = shardingList(list, index, total);
        XxlJobLogger.log(jobs.toString());
        jobs.forEach(n -> {
            log.info(">>>>>>>>>>>   " + n);
            XxlJobLogger.log(">>>>>>>>>>>   " + n);
        });

        return ReturnT.SUCCESS;
    }

    private <T> List<T> shardingList(List<T> list, int index, int total) {
        int start = list.size() / total * index;
        int end = start + list.size() / total;
        if (index + 1 == total) {
            end = list.size();
        }
        return list.subList(start, end);
    }
}
